package biz.yfsoft.app.fastframework.plugin.icbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import biz.yfsoft.app.fastframework.kit.HttpsPost;
import biz.yfsoft.app.fastframework.plugin.BaseFastPlugin;

public class IcbcPayPlugin extends BaseFastPlugin {

	/*~~~~~~基本的常量设置~~~~~~~
	 参数说明： 
	 password:证书拆分时使用的证书口令
	 notifyUrl:支付之后的回调地址，必须是80端口
	 cert:证书存放的位置，需要有2个文件 分别是 .crt 和 .key 2个文件，需要放在同一个目录下，配置时，不要将文件名设置在里面
	 		并以同一个文件名命名，可以是绝对路径地址，则存放相应的路径名；如果是在classes目录下，则需要添加一个classpath:的前缀，如：classpath:hy
	 shopCode:在工行注册的商户代码
	 shopAcc:商城账号
	{"shopAcc":"1103020209200500343""shopCode":"1103EC13759210","password":"123456","notifyUrl":"http://fast.yfsoft.info/fastframework/admin/notify/payNotify","cert":"classpath:hy"}
	 ~~~~~~~~~~~~~~~~~~~~~~~~~*/
	
	@Override
	public boolean start() {
		//生成证书签名
		try {
			String certFile = null,keyFile = null,pfxFile = null;
			String cert = configJson.containsKey("cert")?configJson.getString("cert"):"classpath:hy";
			String pass =  configJson.containsKey("password")?configJson.getString("password"):"123456";
			String domain = configJson.containsKey("domain")?configJson.getString("domain"):"corporbank3.dccnet.com.cn";
			if(cert.startsWith("classpath:")){
				cert = cert.substring(10);
				//配置文件在classes目录中
				String classPath = IcbcPayPlugin.class.getResource("/").getPath();
				cert = classPath + cert;
			}
			certFile = cert + ".crt";
			keyFile = cert +".key";
			pfxFile = cert + ".pfx";
			FileInputStream in1 = new FileInputStream(certFile);
			byte[] bcert = new byte[in1.available()];
			in1.read(bcert);
			in1.close();
			
			FileInputStream in2 = new FileInputStream(keyFile);
			byte[] bkey = new byte[in2.available()];
			in2.read(bkey);
			in2.close();
			
			IcbcPay.config(bcert, bkey,configJson);
			//将ssl的配置进行更新
			HttpsPost.setCert(pfxFile, pass, domain);
			status = Status.ACTIVED;
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		status = Status.EXCEPTION;
		return false;
	}

}
